package org.example.bigwork.service.impl;

import org.example.bigwork.entity.Task;
import org.example.bigwork.mapper.TaskMapper;
import org.example.bigwork.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskMapper taskMapper;


    @Override
    public List<Task> getTasksByClaimStatus(String claimStatus) {
        return taskMapper.findByClaimStatus(claimStatus);
    }


    @Override
    @Transactional
    public boolean updateTaskCompletionStatus(String taskId, String completionStatus) {
        // 检查任务是否存在
        Task existingTask = taskMapper.findById(taskId);
        if (existingTask == null) {
            return false;
        }
        
        try {
            taskMapper.updateCompletionStatus(taskId, completionStatus);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public Map<String, Task> getTaskMap() {
        // 获取所有任务
        List<Task> tasks = taskMapper.findAll();

        // 将任务列表转换为Map，实现O(1)的查找效率
        return tasks.stream().collect(Collectors.toMap(Task::getTaskId, task -> task));
    }

    @Override
    public List<Task> getSortedTasksByWorkload() {
        // 获取所有任务
        List<Task> tasks = taskMapper.findAll();

        // 使用Java Comparator对任务进行排序（按工作量降序）
        return tasks.stream()
                .sorted(Comparator.comparing(Task::getWorkload, Comparator.nullsLast(Comparator.reverseOrder())))
                .collect(Collectors.toList());
    }

} 